package com.atguigu.gmall.pay.service.impl;

import com.atguigu.gmall.common.util.HttpClient;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.feign.OrderFeign;
import com.atguigu.gmall.pay.service.PayService;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


/**
 * 支付service的实现类
 */
@Service
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderFeign orderFeign;

    @Value("${weixin.pay.appid}")
    private String appid;
    @Value("${weixin.pay.partner}")
    private String partner;
    @Value("${weixin.pay.partnerkey}")
    private String partnerkey;
    @Value("${weixin.pay.notifyUrl}")
    private String notifyUrl;
    /**
     * 生成支付二维码
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> createPayImg(Long orderId) {
        //查询订单的详细信息
        OrderInfo orderInfo = orderFeign.getById(orderId);
        //获取订单的金额
        BigDecimal totalAmount = orderInfo.getTotalAmount();
        //将金额转换为分
        BigDecimal wxTotal = totalAmount.multiply(new BigDecimal(100));
        try {
            //请求的url
            String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
            Map<String,String> requestMap = new HashMap<>();
            requestMap.put("appid",appid);
            requestMap.put("mch_id",partner);
            requestMap.put("nonce_str", WXPayUtil.generateNonceStr());
            requestMap.put("body","java0107测试");
            requestMap.put("out_trade_no","java00000000000000000023");
            requestMap.put("total_fee", wxTotal.intValue() + "");
            requestMap.put("spbill_create_ip", "192.168.200.1");
            requestMap.put("notify_url", notifyUrl);
            requestMap.put("trade_type", "NATIVE");
            //将map类型的数据转换为xml格式的字符串
            String xml = WXPayUtil.generateSignedXml(requestMap, partnerkey);
            //发送请求
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);
            httpClient.post();
            //得到结果：xml格式的字符串
            String content = httpClient.getContent();
            //转换为map类型的数据
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            //返回结果
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询支付结果
     *
     * @param orderId
     * @return
     */
    @Override
    public Map<String, String> getPayResult(Long orderId) {
        try{
            //请求的url
            String url = "https://api.mch.weixin.qq.com/pay/orderquery";
            //包装微信统一接口的请求参数
            Map<String, String> requestMap = new HashMap<>();
            requestMap.put("appid", appid);
            requestMap.put("mch_id", partner);
            requestMap.put("nonce_str", WXPayUtil.generateNonceStr());
            requestMap.put("out_trade_no", "java00000000000000000023");
            //将map类型的数据转换为xml格式的字符串
            String xml = WXPayUtil.generateSignedXml(requestMap, partnerkey);
            //发送请求
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);
            httpClient.post();
            //得到结果:xml格式的字符串
            String content = httpClient.getContent();
            //转换为map类型的数据
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            //返回结果
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 关闭交易
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean closePay(Long orderId) {
        try {
            //请求的url
            String url = "https://api.mch.weixin.qq.com/pay/closeorder";
            //包装微信统一接口的请求参数
            Map<String,String> requestMap = new HashMap<>();
            requestMap.put("appid", appid);
            requestMap.put("mch_id", partner);
            requestMap.put("nonce_str", WXPayUtil.generateNonceStr());
            requestMap.put("out_trade_no", "java00000000000000000023");
            //将map类型的数据转换为xml格式的字符串
            String xml = WXPayUtil.generateSignedXml(requestMap, partnerkey);
            //发送请求
            HttpClient httpClient = new HttpClient(url);
            httpClient.setHttps(true);
            httpClient.setXmlParam(xml);
            httpClient.post();
            //得到结果:xml格式的字符串
            String content = httpClient.getContent();
            //转换为map类型的数据
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            if (map.get("return_code").equals("SUCCESS") && map.get("result_code").equals("SUCCESS")){
                return true;
            }
            //返回结果
            return false;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
